<script lang="ts">
  import { setContext } from "svelte";
  import { writable } from "svelte/store";
  import type { BreadcrumbItem, BreadcrumbContext } from "./conf";
  import Breadcrumb from "./Breadcrumb.svelte";
  import Sep from "./Sep.svelte";
  export let data: string;
  export let rootLabel = "root";
  export let baseHref = "";
  const activeBreadcrumb$ = writable(0);
  const breadcrumbs$ = writable<BreadcrumbItem[]>([]);
  
  $: {
    parseData(data);
  }

  setContext<BreadcrumbContext>("breadcrumbs", {
    activeBreadcrumb$,
    addBreadcrumb,
    clickBreadcrumb,
    getIndex,
  });

  function addBreadcrumb(item: BreadcrumbItem): number {
    const index = $breadcrumbs$.length;
    breadcrumbs$.set([...$breadcrumbs$, item]);
    return index;
  }
  function getIndex(item: BreadcrumbItem): number {
    return $breadcrumbs$.findIndex(v => v.label === item.label && v.href === item.href);
  }
  // $: _clickBreadcrumb(active);
  function _clickBreadcrumb(index: number) {
    console.log('index:',index, $breadcrumbs$.length)
    if (
      index < 0 ||
      ($breadcrumbs$.length > 0 && index >= $breadcrumbs$.length)
    ) {
      console.warn("breadcrumbIndex invalid");
      return;
    }
    breadcrumbs$.set($breadcrumbs$.slice(0, index + 1));

    activeBreadcrumb$.set(index);
  }
  function clickBreadcrumb(index: number) {
    _clickBreadcrumb(index);
  }

  // /a/b => [{label: '/', path: '/'}, {label: 'a', path: '/a'}, {label: 'b', path: '/a/b'},]
  function parseData(data: string) {
    let breadcrumbs: BreadcrumbItem[] = [{label: rootLabel, href: baseHref}];
    if (data.substring(0, 1) == "/") {
      data = data.substring(1)
    }
    const arr = data.split("/");
    let parentHref = baseHref
    for(let str of arr){
      if (str.length>0) {
        breadcrumbs.push({label: str, href: `${parentHref}/${str}`})
        parentHref = breadcrumbs[breadcrumbs.length-1].href
      }
    }
    // console.log('breadcrumbs=>', breadcrumbs, data);
    breadcrumbs$.set(breadcrumbs);
    activeBreadcrumb$.set(breadcrumbs.length - 1);
  }

</script>

<ul class="breadcrumbs-container">
  <!-- <Breadcrumb item={{label: "/", path: "/" }} ></Breadcrumb> -->
  {#each $breadcrumbs$ as item, index}
    <Breadcrumb {item} >
      {#if $$slots.default}
        <slot {item} />
      {:else}
        {item.label}
      {/if}
    </Breadcrumb>
    <Sep hidden={index === $breadcrumbs$.length - 1}>
      {#if $$slots.sep}
        <slot name="sep" />
      {:else}
        /
	    {/if}
    </Sep>
  {/each}
</ul>

<style lang="postcss">
  :root {
    --breadcrumbs-height: 100%;
  }
  .breadcrumbs-container {
    @apply flex justify-start items-center w-full grow-0;
  }
</style>
